package com.starhub.application.rag.store;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.starhub.application.rag.service.MilvusFlushService;

/**
 * Milvus连接清理定时任务
 * 用于定期清理和刷新连接，防止连接泄漏
 * 
 * @version: V1.0
 * @author: liuhf
 */
@Slf4j
@Component
public class ConnectionCleanupTask {

    @Autowired
    private LangchainStoreBuilder langchainStoreBuilder;

    @Autowired
    private MilvusFlushService milvusFlushService;

    /**
     * 定期清理连接
     * 每30分钟执行一次
     */
    @Scheduled(fixedRate = 30 * 60 * 1000) // 30分钟
    public void cleanupConnections() {
        try {
            log.info("Starting scheduled Milvus connection cleanup...");
            langchainStoreBuilder.refreshAllConnections();
            log.info("Scheduled Milvus connection cleanup completed");
        } catch (Exception e) {
            log.error("Error during scheduled Milvus connection cleanup", e);
        }
    }

    /**
     * 应用启动时的连接健康检查
     * 延迟5秒后执行，确保应用完全启动
     */
    @Scheduled(initialDelay = 5000, fixedRate = Long.MAX_VALUE)
    public void initialHealthCheck() {
        try {
            log.info("Performing initial Milvus connection health check...");
            // 启动定时刷新服务
            milvusFlushService.startScheduledFlush();
            log.info("Initial Milvus connection health check completed");
        } catch (Exception e) {
            log.error("Error during initial Milvus connection health check", e);
        }
    }
} 